import React, { useState, useEffect, useRef } from 'react';
import { connect, FormattedMessage, useIntl } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Tabs, Card, message, Modal, Tag, Checkbox } from 'antd';

import { EmpSelectCmp } from '@/components/FormItemSelect';
import MfgMtlSearch from '../manufacture/MfgMtlSearch';
import request from '@/utils/request';
import MyDataTable from '@/components/MyDataTable';
import PrintModal from '@/components/PrintModal';
import TempleteIssue from '../PrintTemplete/TempleteIssue';
import QuickMenu from '@/components/QuickMenu';
import type { ProColumns } from '@ant-design/pro-table';
import OperpQuery from '@/components/OperpQuery';

const apiURLApp = '/api/services/app/JobMtl/';
const { TabPane } = Tabs;

type DataType = {
  key: React.Key;
  partNum: string;
  partDescription: string;
  reqQty: number;
  ium: string;
  reqDate: string;
  warehouseCode: string;
  binNum: string;
  id: string;
  pickQty: number;
  pickUser: string;
  pickedQty: number;
  pickType: string;
  completeQty: number;
};

const STKMtl: React.FC<any> = (props) => {
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [visible, setVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [params, setParams] = useState({ apprv: 1, open: 1 });
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [selectedEmp, setSelectedEmp] = useState('');
  const [printData, setPrintData] = useState([]);
  const [freshNum, setFreshNum] = useState(0);
  const [PickNum, setPickNum] = useState('0');
  const [actTab, setActTab] = useState('1');
  const [visible2, setVisible2] = useState(false);
  const [editSelectRow, setEditSelectRow] = useState<any>(null);
  const printArea = useRef(null);
  const intl = useIntl();

  useEffect(() => {
    // componentDidMount
  }, []);

  const handleSearch = (params: any) => {
    params.apprv = 1;
    params.open = 1;
    setParams(params);
    setFreshNum(freshNum + 1);
  };

  const switchVisible = (visible = false) => {
    if (selectedRows.length <= 0) {
      message.error(intl.formatMessage({ id: 'pages.select.material' }));
    } else {
      setVisible(visible);
    }
  };

  const handleRowSelect = (selectedKeys: any, selectedRows: any) => {
    setSelectedKeys(selectedKeys);
    setSelectedRows(selectedRows);
  };

  const handleSubmit = async () => {
    if (selectedRows.length <= 0) {
      return message.warning(intl.formatMessage({ id: 'pages.select.material' }));
    }
    if (!selectedEmp) {
      return message.warning(intl.formatMessage({ id: 'pages.select.pickUser' }));
    }
    let isok = true;
    let err = 0;
    selectedRows.forEach((item: DataType) => {
      if (item.pickQty == 0 || !item.pickQty) {
        err++;
      }
    });
    if (err > 0) {
      isok = false;
      return message.warning(intl.formatMessage({ id: 'pages.fill.pickQty' }));
    }
    const data: any = [];
    selectedRows.forEach((item: DataType) => {
      data.push({
        pickUser: selectedEmp,
        pickType: 'STK',
        jobNum: '0',
        reqNum: item.id,
        requiredQty: item.reqQty,
        partNum: item.partNum,
        partDescription: item.partDescription,
        pickQty: item.pickQty,
        ium: item.ium,
      });
      if (item.pickQty > item.reqQty - item.completeQty) {
        message.warning(intl.formatMessage({ id: 'pages.pickQty.exceed' }));
        isok = false;
      }
    });

    if (isok) {
      const resp = await request(apiURLApp + 'AppIssueMtl', {
        method: 'POST',
        data,
      });
      if (resp && resp.success) {
        message.success(intl.formatMessage({ id: 'pages.pick.success' }));
        setPickNum(resp.result);
        setFreshNum(freshNum + 1);
      }
      setPrintData(selectedRows);
      switchVisible();
    }
  };

  const selectEmp = (values: any) => {
    setSelectedEmp(values);
  };

  const doPrint = () => {
    setVisible2(true);
  };

  const quickFill = () => {
    dataSource.forEach((item: any) => {
      item.pickQty = item.reqQty;
    });
    setDataSource([...dataSource]);
  };

  const delAppMtl = () => {
    const ids: any = [];
    printData.forEach((item: any) => {
      ids.push(item.id);
    });
    request(apiURLApp + 'DelAppMtl', {
      method: 'POST',
      data: ids,
    }).then(() => {
      setFreshNum(freshNum + 1);
    });
  };

  const doComplete = () => {
    const ids: any = [];
    printData.forEach((item: any) => {
      ids.push(item.id);
    });
    request(apiURLApp + 'BatchComplete', {
      method: 'POST',
      data: ids,
    }).then(() => {
      setFreshNum(freshNum + 1);
    });
  };

  const checkQty = (rule: any, value: any, callback: any) => {
    if (value) {
      if (editSelectRow.reqQty - editSelectRow.completeQty < value || value <= 0) {
        callback(intl.formatMessage({ id: 'pages.pickQty.exceed' }));
      } else {
        callback();
      }
    } else {
      callback(<FormattedMessage id="pages.pickQty.required" />);
    }
  };

  const responseFun = (response: any) => {
    response?.result?.items.forEach((element: DataType) => {
      element.pickQty = element.reqQty - element.completeQty;
    });
    return response;
  };

  const columns: ProColumns<DataType>[] = [
    {
      title: <FormattedMessage id="pages.reqNum" />,
      dataIndex: 'id',
      align: 'center',
      width: 80,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      align: 'left',
      width: 120,
      editable: false,
      copyable: true,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
      width: 200,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.reqQty" />,
      dataIndex: 'reqQty',
      align: 'center',
      width: 100,
      valueType: 'digit',
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.pickedQty" />,
      dataIndex: 'completeQty',
      align: 'center',
      width: 100,
      valueType: 'digit',
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'ium',
      align: 'center',
      width: 100,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.pickQty" />,
      dataIndex: 'pickQty',
      valueType: 'digit',
      width: 120,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            validator: checkQty,
          },
        ],
      },
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      fixed: 'right',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            setEditSelectRow(record);
            action?.startEditable?.(record.id);
          }}
        >
          <FormattedMessage id="pages.pick" />
        </a>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs defaultActiveKey="1" onChange={(e) => setActTab(e)}>
          <TabPane tab={<FormattedMessage id="pages.pick" />} key="1">
            <MyDataTable
              act="GetList"
              columns={columns}
              freshNum={freshNum}
              pageSize={pageSize}
              control="Demands"
              rowSelection={{
                selectedRowKeys: selectedKeys,
                onChange: handleRowSelect,
              }}
              params={params}
              bordered={false}
              toolBarRender={() => [
                <Tag color="processing">
                  <FormattedMessage id="pages.pickNum" />：{PickNum}
                </Tag>,
                <MfgMtlSearch onSearch={handleSearch} hideSearchItem={false} />,
                <EmpSelectCmp
                  width={100}
                  name="empId"
                  label={<FormattedMessage id="pages.pickUser" />}
                  onChange={selectEmp}
                  showSearch
                />,
                <Button type="primary" onClick={handleSubmit}>
                  <FormattedMessage id="pages.appPick" />
                </Button>,
                <Button type="primary" onClick={quickFill}>
                  <FormattedMessage id="pages.fillAll" />
                </Button>,
                <QuickMenu path="/part/STKMtl" icon="icon-document" title="pages.PickSTKMtl" />,
              ]}
              pagination={true}
              editable={{
                type: 'multiple',
                actionRender: (row: any, config: any, dom: { save: any; cancel: any }) => [
                  dom.save,
                  dom.cancel,
                ],
                onSave: async (
                  rowKey: any,
                  data: { pickQty: number },
                  row: { reqQty: number },
                ) => {
                  data.pickQty = data.pickQty > row.reqQty ? row.reqQty : data.pickQty;
                },
              }}
              responseFun={(response: any) => responseFun(response)}
            />
          </TabPane>
          <TabPane tab={<FormattedMessage id="pages.pickHistory" />} key="2">
            <OperpQuery
              rowSelection={{
                onChange: (_selectedKeys: any, selectedRows: any) => {
                  setPrintData(selectedRows);
                },
              }}
              sysReportName="ReportIssueMtl"
              scroll={{ x: 'max-content', y: '600px' }}
              freshNum={freshNum}
              toolBarRender={[
                <Button type="primary" onClick={doPrint}>
                  <FormattedMessage id="pages.print" />
                </Button>,
                <Button danger onClick={delAppMtl}>
                  <FormattedMessage id="pages.revoke" />
                </Button>,
                <Button type="default" onClick={doComplete}>
                  <FormattedMessage id="pages.complete" />
                </Button>,
              ]}
            />
          </TabPane>
        </Tabs>
      </Card>
      <div ref={printArea} hidden>
        <TempleteIssue data={printData} ref={printArea} hidden />
      </div>
      <Modal
        width={1024}
        title={<FormattedMessage id="pages.pickListPrint" />}
        visible={visible2}
        destroyOnClose={true}
        onCancel={() => setVisible2(false)}
        footer={false}
      >
        <PrintModal>
          <TempleteIssue data={printData} configData={props.currentConfig} />
        </PrintModal>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentConfig: user.currentConfig,
}))(STKMtl);
